package com.clps.threadPool.test01;

import com.google.common.collect.Lists;
import org.apache.commons.collections.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;

public class ChildTask {

    private final  int POOL_SIZE = 2;//线程池大小
    private final  int SPLIT_SIZE = 4;//线程池大小

    private  String taskName;

    //接受jvm关闭信号,实现优雅停机
    protected  volatile  boolean terminal= false;

    public ChildTask(String taskName) {
        this.taskName = taskName;
    }

    //程序执行的入口
    public  void doExecute(){
        int i = 0;
        while (true){
            System.out.println(taskName + ":Cycle-" + i + "-Begin");
            //获取数据
            List<Cat> datas = quaryData();
            //处理数据
            taskExecute(datas);
            System.out.println("datas = " + datas);
            if(terminal){
                //只有应用关闭,才会走到这里,用于实现优雅的下线
                break;
            }
            i++;
        }
        //回收线程池资源
        TaskProcessUtil.releaseExecutors(taskName);
    }

    private void taskExecute(List<Cat> sourceDatas) {
        if(CollectionUtils.isEmpty(sourceDatas)){
            return;
        }
        //将拆分的数据拆成三份
        List<List<Cat>> splitDatas = Lists.partition(sourceDatas, SPLIT_SIZE);
        final CountDownLatch latch = new CountDownLatch(splitDatas.size());
        //并发处理拆分的数据,共用一个先后才能池
        for (final List<Cat> datas  : splitDatas) {
            ExecutorService executorService = TaskProcessUtil.getOrInitExecutors(taskName, POOL_SIZE);
            executorService.submit(new Runnable() {
                @Override
                public void run() {
                    //doProcessData(datas, latch);
                }
            });
        }
        try {
            latch.await();
        } catch (Exception e) {
            System.out.println(e.getStackTrace());
        }

    }

    private List<Cat> quaryData() {
       List<Cat> datas  = new ArrayList<>();
        for (int i = 0; i <5 ; i++) {
            datas.add(new Cat().setCatName("罗小黑"+1));
        }
        return datas;
    }

    public void terminal() {
    }
}
